package cn.tedu.ivos.audit.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos.audit.pojo.entity.Audit;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.base.enums.AuditStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

/**
 * @Transactional是Spring提供的一个用于管理事务的注解,用来管理类或方法上的事务行为 在对数据库做操作时, 可以确保方法中的所有数据库操作都在同一个事务中执行, 要么都成功, 要么都失败
 */
@Transactional
@Slf4j
@Service
public class AuditServiceImpl implements AuditService {
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ApplicationMapper applicationMapper;

    @Override
    public void insertAudit(Application application) {
        log.debug("为申请单生成审批单业务，参数：{}", application);
        //1.获取审批人id集合
        List<Long> userIdList = application.getAuditUserIdList();
        //2.遍历id集合
        for (int i = 0; i < userIdList.size(); i++) {
            //3.有几个审批人id,就生成几条审批数据
            Audit audit = new Audit();
            //4.1设置申请单id
            audit.setApplicationId(application.getId());
            //4.2设置审批人id
            audit.setAuditUserId(userIdList.get(i));
            //4.3设置审批次序
            audit.setAuditSort(i);
            //4.4设置审批状态
            if (i == 0) {
                audit.setAuditStatus(AuditStatusEnum.MY_PENGDING.getCode());
            } else {
                audit.setAuditStatus(AuditStatusEnum.PENGDING.getCode());
            }
            //4.5设置新增时间
            audit.setCreateTime(new Date());
            //5.将准备好的审批单入库
            auditMapper.insert(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long id) {
        return auditMapper.selectAuditByApplicationId(id);
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        log.debug("查询审批单业务，参数：{}", auditQuery);
        List<AuditVO> list = auditMapper.selectAudit(auditQuery);
        for (int i = 0; i < list.size(); i++) {
            AuditVO auditVO = list.get(i);
            assignAuditUserList(auditVO);
        }
        return list;
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        log.debug("更新审批业务，参数：{}", auditSaveParam);
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam, audit);
        audit.setUpdateTime(new Date());
        //更新当前的这个审批单,审批单的状态是30还是40是由前端传过来的
        auditMapper.update(audit);
        //准备更新此审批单对应的申请单
        Application application = new Application();
        application.setId(audit.getApplicationId());
        application.setUpdateTime(new Date());
        /* 判断是通过处理还是驳回处理 */
        if (audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())) {//通过处理
            //1.继续查当前审批单对应的其它审批单(与当前审批单批同一个申请单)
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            //2.根据申请单id,查出此申请单对应的所有未审批的审批单总数
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            if (count > 0) {
                //还有未审批的审批单
                //3.根据申请单id与审批次序+1找到下一条未审批的审批单
                auditQuery.setAuditSort(audit.getAuditSort() + 1);
                List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
                if (auditVOList != null && auditVOList.size() > 0) {
                    AuditVO auditVO = auditVOList.get(0);
                    //4.准备更新第2条审批单
                    Audit Audit2 = new Audit();
                    Audit2.setId(auditVO.getId());
                    Audit2.setAuditStatus(AuditStatusEnum.MY_PENGDING.getCode());
                    Audit2.setUpdateTime(new Date());
                    auditMapper.update(Audit2);
                }
                //5.更新申请单
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
            } else {
                //刚刚更新的审批单是最后一个审批单了
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }
        } else if (audit.getAuditStatus().equals(AuditStatusEnum.REJECT.getCode())) {//驳回处理
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
            if (auditVOList != null && auditVOList.size() > 0) {
                for (int i = 0; i < auditVOList.size(); i++) {
                    AuditVO auditVO = auditVOList.get(i);
                    if(auditVO.getAuditStatus().equals(AuditStatusEnum.PENGDING.getCode())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.update(application);
        }
    }

    private void assignAuditUserList(AuditVO auditVO) {
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        //根据传入的审批单获取其对应的申请单id,查询此申请单下所有的审批单
        List<AuditVO> auditVOList =
                auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        //遍历每个审批单对象
        for (int i = 0; i < auditVOList.size(); i++) {
            Long userId = auditVOList.get(i).getAuditUserId();
            auditUserIdList.add(userId);
            UserVO userVO = userMapper.selectById(userId);
            auditUsernameList.add(userVO.getUsername());
        }
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String username : auditUsernameList) {
            stringJoiner.add(username);
        }
        auditVO.setAuditUserIdList(auditUserIdList);
        auditVO.setAuditUsernameList(stringJoiner.toString());
    }
}
